package com.jdew.thkj.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.util.Base64;
import android.view.View;

public class BitmapUtil {
    private static final String TAG = "BitmapUtil";

    /**
     * 从本地获取图片
     * <p>
     * 通过文件名获取本地图片,reqWidth和reqWidth为期望返回图片的宽度和高度
     * 如果值希望按照reqWidth计算,可将reqHeight设置为0,反之亦反 如果两个都为0,则不缩放
     */
    public static Bitmap getBitmapFromLocal(String filepath, int reqWidth,
                                            int reqHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filepath, options);
        if (reqHeight == 0 && reqWidth == 0) {
            options.inSampleSize = 1;
        } else {
            options.inSampleSize = caculateInSimpleSize(options, reqWidth,
                    reqHeight);
        }
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filepath, options);
    }

    /**
     * 计算缩放比例
     */
    private static int caculateInSimpleSize(Options options, int reqWidth,
                                            int reqHeight) {
        int inSimpleSize = 1;
        int width = options.outWidth;
        int height = options.outHeight;
        if (reqWidth < width || reqHeight < height) {
            int widthScale = Math.round(((float) width / (float) reqWidth));
            int heightScale = Math.round(((float) height / (float) reqHeight));
            inSimpleSize = heightScale < widthScale ? heightScale : widthScale;
        }
        return inSimpleSize;
    }

    /**
     * 从网络获取图片
     */
    public static Bitmap getBitmapFromUrl(String url) {
        Bitmap resutBitmap = null;
        InputStream is = null;
        try {
            URL addresUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) addresUrl
                    .openConnection();
            conn.setReadTimeout(5 * 1000);
            conn.setConnectTimeout(5 * 1000);
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                is = conn.getInputStream();
                resutBitmap = BitmapFactory.decodeStream(is);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resutBitmap;
    }

    /**
     * 旋转图片 type: 1 竖屏显示 type: 2横屏显示
     */
    public static Bitmap getRotateBitmap(int type, String bitmapPath) {
        Bitmap bitmap = BitmapFactory.decodeFile(bitmapPath);
        Bitmap resultBitmap = bitmap;
        int height = bitmap.getHeight();
        int width = bitmap.getWidth();
        switch (type) {
            case 1:
                if (height < width) {
                    Matrix mmMatrix = new Matrix();
                    mmMatrix.postRotate(90f);
                    resultBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                            bitmap.getWidth(), bitmap.getHeight(), mmMatrix, true);
                }
                break;
            case 2:
                if (height > width) {
                    Matrix mmMatrix = new Matrix();
                    mmMatrix.postRotate(90f);
                    resultBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                            bitmap.getWidth(), bitmap.getHeight(), mmMatrix, true);
                }
                break;
            default:
                break;
        }
        return resultBitmap;
    }

    /**
     * 保存bitmap到硬盘上
     */
    public static boolean saveBitmapToFile(Bitmap bitmap, String filename) {
        return saveBitmapToFile(bitmap, filename, 100);
    }

    /**
     * 保存bitmap到硬盘上,
     *
     * @param quality 100为不压缩
     */
    public static boolean saveBitmapToFile(Bitmap bitmap, String filename,
                                           int quality) {
        String suffix = filename.substring(filename.lastIndexOf("."))
                .toLowerCase();
        CompressFormat format = null;
        if (suffix.equals(".png")) {
            format = Bitmap.CompressFormat.PNG;
        } else {
            format = Bitmap.CompressFormat.JPEG;
        }
        OutputStream os = null;
        try {
            File file = new File(filename);
            if (file.exists()) {
                file.delete();
            }
            os = new FileOutputStream(file);
            return bitmap.compress(format, quality, os);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * drawable转换为bitmap
     */
    public static Bitmap decodeResource(Context context, int resourseId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
// 获取资源图片
        InputStream is = context.getResources().openRawResource(resourseId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    /**
     * assets目录下文件转bitmap
     */
    public static Bitmap decodeBitmapFromAssets(Context context, String resName) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;
        InputStream in = null;
        try {
            in = context.getAssets().open(resName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return BitmapFactory.decodeStream(in, null, options);
    }

    /**
     * 回收不需要的bitmap
     */
    public static void recycleBitmap(Bitmap b) {
        if (b != null && !b.isRecycled()) {
            b.recycle();
            b = null;
        }
    }

    /**
     * 把bitmap转成 Bytes数组
     */
    public static byte[] BitmapToBytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * bytes数组转bitmap
     */
    public static Bitmap BytesToBitmap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        }
        return null;
    }

    /**
     * bitmap转string
     */
    public static String bitmaptoString(Bitmap bitmap) {
        String string = null;
        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 100, bStream);
        byte[] bytes = bStream.toByteArray();
        string = Base64.encodeToString(bytes, Base64.DEFAULT);
        return string;
    }

    /**
     * string转bitmap
     */
    public static Bitmap stringToBitmap(String string) {
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
                    bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public static Bitmap viewToBitmap(View view) {
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }

}
